<template>
    <div class="search">
        <slot name="search" :searchSubmit="searchSubmit" :params="params"></slot>
    </div>
    <div class="fun">
        <slot :deleteAllHandle="deleteAllHandle" name="buttons"></slot>
    </div>
    <div class="table">
        <el-table  v-loading="loading" @selection-change="selectionChange" :data="state.list" style="width: 100% ;line-height: 50px;">
            <el-table-column v-if="porps.isSelection" type="selection" width="40" />
            <el-table-column
             v-for="column in porps.column"
              :prop="column.prop" 
              :fixed="column.prop=='operate'?'right':false"  
              :label="column.lable" 
              v-bind="column.attrs"
              > 
              <template v-if="column.slot" #default="scope">
                    <slot :name="column.prop"  :scope="scope"  :delrow="delrow">
                    </slot>
                </template>
                <template v-if="column.date" #default="scope">
                    {{ formData(scope.row[column.prop] ) }}
                </template>
                <template v-if="column.image" #default="scope">
                    <el-image style="width: 60px; height: 60px" :src="baseUrl + scope.row[column.prop]" :zoom-rate="1.2"
                    :max-scale="5" :min-scale="0.2"
                    :preview-src-list="['http://api.quanjiu.net/estate/upload/' + scope.row[column.prop]]" :initial-index="4"
                    preview-teleported fit="cover" />
                </template>
                <template v-if="column.images" #default="scope">
                    <el-image v-for="item in scope.row[column.prop]"
                     style="width:50px; height: 50px ;margin-left: 5px; " :src="baseUrl + item.url" :zoom-rate="1.2"
                    :max-scale="5" :min-scale="0.2"
                    :preview-src-list="scope.row[column.prop].map((item: any) => baseUrl + item.url)" :initial-index="4"
                    preview-teleported fit="cover" />
                </template>
                
            </el-table-column>
        </el-table>
    </div>
    <div class="page">
        <el-pagination v-if="porps.pageConfig.isShow" v-model:current-page="params.page" v-model:page-size="params.psize"
            :page-sizes="[15, 30, 50, 100]" background layout="total, sizes, prev, pager, next, jumper"
            :total="state.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
</template>

<script lang='ts' setup>

import { onMounted, reactive,ref } from 'vue';
import { ElMessage,ElMessageBox } from 'element-plus';
import moment  from 'moment';

const baseUrl = import.meta.env.VITE_IMG_URL
const loading = ref(false)
const emit = defineEmits(["selectChange"])

//日期
const formData = (a: string) => {
  return moment(a).format('YYYY-MM-DD');
}
//多选改变
const selectionChange = (e:any)=>{
    selectData.value=e
    emit("selectChange",e)
    ids.value = selectData.value.map(item => item.id)
}
const selectData = ref<any[]>([])
let ids =ref<number[]>([])
//单删
const delrow = async (id: number) => {
    const confirm = await ElMessageBox.confirm('是否要删除选中的记录?').catch(() => { })
  if (!confirm) return;
    const res: any = await porps.delDate(id)
    console.log(res);
    if (res.errCode === 10000) {
        ElMessage({
            message: '删除成功',
            type: 'success',
        })
        //重新获取数据
        getlist()
    }
}
//全选删除
const deleteAllHandle = async () => {
    if (ids.value.length === 0) {
        return ElMessage({
            message: '请选择要删除的数据',
            type: 'error',
        })
    }
    const confirm = await ElMessageBox.confirm('是否要删除选中的记录?').catch(() => { })
  if (!confirm) return;
    const res: any = await porps.delallDate(ids.value)
    if (res.errCode === 10000) {
        ElMessage({
            message: '删除成功',
            type: 'success',
        })
    }
    getlist()
}
//查询
 const searchSubmit = async () => {
    params.page = 1
    getlist()
}
//暴露方法
defineExpose({ searchSubmit})
//列表项类型
type ColumnType = {
    prop: string
    lable: string
    slot: boolean
    attrs?: any
    image?: boolean
    images?: boolean
    date?: boolean
}
//列表参数
const state = reactive({
    total: 0,
    list: []
})
type PageConfig = {
  psize?: number,
  isShow?: boolean,
  pageSizes?: number[],
}
//列表类型
export type TableType = {
    column: Array<ColumnType>
    isSelection?: boolean
    loadData: Function
    delallDate?: Function
    delDate?: Function
    searchParams?:any
    pageConfig?:PageConfig
}
//传值
const porps = withDefaults(defineProps<TableType>(), {
    column: () => [],
    loadData: () => () => { },
    delDate:()=>()=>{},
    delallDate: () => () => { },
    isSelection: ()=> true,
    searchParams:()=>({}),
    pageConfig: () => ({
    psize: 15,
    isShow: true,
    pageSizes: [15, 30, 50, 100, 300]
  })
})
 if (porps.pageConfig.psize == undefined) {
    porps.pageConfig.psize = 15;
}
if (porps.pageConfig.isShow == undefined) {
    porps.pageConfig.isShow = true;
}
if (porps.pageConfig.pageSizes == undefined) {
    porps.pageConfig.pageSizes = [15, 30, 50, 100, 300];
}

// const isSelection=ref(true)
const params = reactive<any>({
  page: 1,
  psize: porps.pageConfig.psize

})
//获取列表

const getlist = async () => {
    loading.value = true
    let _params={...porps.searchParams,...params};
    let res = await porps.loadData(_params)
    if (res.errCode === 10000) {
        loading.value = false
        state.list = res.data.list
        state.total = res.data.counts
    }
}
//分页方法
const handleSizeChange = (val: number) => {
    params.psize = val
    getlist()
}
const handleCurrentChange = (val: number) => {
    params.page = val
    getlist()
}

onMounted(() => {
    getlist()
})
</script>

<style lang="less" scoped>
.fun{
    width: 100%;
    margin: 20px;
}
.table{
    width: 100%;
}
.page{
    margin-top: 20px;
}
</style>
